package com.atguigu.edu.realtime.common.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {
    public static Connection getMySqlConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 建立连接
        Connection conn = DriverManager.getConnection( "jdbc:mysql://hadoop102:3306?useSSL=false", "root", "000000");

        return conn;
    }

    //关闭连接
    public static void closeMySqlConnection(Connection conn) throws Exception {
        if (conn!=null&&!conn.isClosed()){
            conn.close();
        }
    }

    //通用从MySql表中查询数据
    public static <T>List<T> queryList(Connection conn,String sql,Class<T> clz) throws Exception {
        return queryList(conn,sql,clz,false);
    }
    public static <T>List<T> queryList(Connection conn,String sql,Class<T> clz,boolean isUnderLineToCamel) throws Exception {
        List<T> realList=new ArrayList<>();
        //获取数据库操作对象
        PreparedStatement ps=conn.prepareStatement(sql);
        //执行SQL
        ResultSet rs = ps.executeQuery();
        //处理结果集
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()){
            T obj = clz.newInstance();
            for (int i = 1; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);

                if (isUnderLineToCamel){
                    columnName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName);
                }

                BeanUtils.setProperty(obj,columnName,columnValue);
            }
            realList.add(obj);
        }
        //释放资源
        rs.close();
        ps.close();
        return realList;

    }

}
